<template>
  <div class="asset-tasks-management">
    <!-- 全局统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">📊 任务统计</h2>
      <div class="stats-container">
        <StatisticCard
          label="总任务数"
          :value="globalStats.total_tasks.toString()"
          icon="el-icon-document"
          type="primary"
        />
        <StatisticCard
          label="疑似资产总数"
          :value="globalStats.total_suspected.toString()"
          icon="el-icon-warning"
          type="warning"
        />
        <StatisticCard
          label="已推理总数"
          :value="globalStats.total_inferred.toString()"
          icon="el-icon-cpu"
          type="info"
        />
        <StatisticCard
          label="已确认总数"
          :value="globalStats.total_confirmed.toString()"
          icon="el-icon-check"
          type="success"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div class="list-header">
        <div class="header-left">
          <h3 class="list-title">资产任务列表</h3>
        </div>
        <div class="header-right">
          <span class="sort-label">排序:</span>
          <el-select
            v-model="filterForm.sort_by"
            size="small"
            style="width: 140px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="按扫描时间" value="scan_time" />
            <el-option label="按任务ID" value="task" />
            <el-option label="按疑似数量" value="suspected_count" />
          </el-select>
          <el-select
            v-model="filterForm.sort_order"
            size="small"
            style="width: 80px"
            @change="handleSearch"
          >
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </div>
      </div>

      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="taskList"
          :columns="tableColumns"
          :loading="false"
          border
          row-key="task"
        >
          <template #task_type="{ row }">
            <el-tag
              :type="row.task_type === 'auto' ? 'success' : 'info'"
              size="small"
            >
              {{ row.task_type === "auto" ? "自动" : "手动" }}
            </el-tag>
          </template>

          <template #high_risk="{ row }">
            <el-tag
              v-if="row.high_risk_stats?.has_high_risk"
              type="danger"
              size="small"
            >
              高危 {{ row.high_risk_stats.high_risk_count }}个
            </el-tag>
            <span v-else class="no-risk">无</span>
          </template>

          <template #action="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
          </template>
        </DynamicTable>

        <el-empty
          v-if="!loading && taskList.length === 0"
          description="暂无任务数据"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          :total="pagination.total"
          :layout="pagination.layout"
          :background="pagination.background"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 任务详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :task-detail="taskDetail"
      :loading="detailLoading"
      @export-report="handleExportReport"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import {
  getAssetTasks,
  getAssetTaskDetail,
  exportAssetTaskReport,
} from "../../servers";
import DetailModal from "./components/DetailModal.vue";

// 页面状态
const isFilterExpanded = ref(true);
const loading = ref(false);
const detailVisible = ref(false);
const currentTask = ref<any>(null);
const taskDetail = ref<any>(null);
const detailLoading = ref(false);

// 全局统计信息
const globalStats = reactive({
  total_tasks: 0,
  total_suspected: 0,
  total_inferred: 0,
  total_confirmed: 0,
});

// 任务列表数据
const taskList = ref<
  Array<{
    task: string;
    task_name: string;
    task_type: "auto" | "manual";
    scan_time: string;
    scan_duration: number;
    asset_stats: {
      consistent: { count: number; percentage: number };
      unreported: { count: number; percentage: number };
      suspected: { count: number; percentage: number };
      total: number;
    };
    inference_progress: {
      not_inferred: number;
      inferred: number;
      confirmed: number;
      rejected: number;
      progress_percentage: number;
    };
    high_risk_stats?: {
      high_risk_count: number;
      has_high_risk: boolean;
    };
    created_by: string;
    remark: string | null;
  }>
>([]);

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  keyword: "",
  date_range: 7,
  has_suspected: null as boolean | null,
  sort_by: "scan_time",
  sort_order: "desc",
});

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "keyword",
    name: "任务ID/名称",
    type: "input",
    placeholder: "请输入任务ID或名称关键词",
    col: { span: 6 },
  },
  {
    key: "date_range",
    name: "时间范围",
    type: "select",
    placeholder: "请选择时间范围",
    params: { clearable: false },
    options: [
      { label: "最近7天", value: 7 },
      { label: "最近30天", value: 30 },
      { label: "最近90天", value: 90 },
      { label: "全部", value: 0 },
    ],
    col: { span: 6 },
  },
  {
    key: "has_suspected",
    name: "疑似资产",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: null },
      { label: "有疑似", value: true },
      { label: "无疑似", value: false },
    ],
    col: { span: 6 },
  },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "任务ID",
    prop: "task",
    minWidth: 150,
    fixed: "left",
  },
  {
    label: "任务名称",
    prop: "task_name",
    minWidth: 200,
  },
  {
    label: "任务类型",
    prop: "task_type",
    minWidth: 100,
    align: "center",
    slot: "task_type",
  },
  {
    label: "扫描时间",
    prop: "scan_time",
    minWidth: 160,
  },
  {
    label: "扫描耗时",
    prop: "scan_duration",
    minWidth: 100,
    align: "center",
    formatter: (row) => {
      return `${row.scan_duration}秒`;
    },
  },
  {
    label: "高危资产",
    prop: "high_risk_stats",
    minWidth: 120,
    align: "center",
    slot: "high_risk",
  },
  {
    label: "创建者",
    prop: "created_by",
    minWidth: 100,
  },
  {
    label: "备注",
    prop: "remark",
    minWidth: 150,
    showOverflowTooltip: true,
  },
  {
    label: "操作",
    width: 120,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取任务列表
const fetchTaskList = async (values?: any) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
      ...values,
    };

    // 处理筛选参数
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }
    if (filterForm.date_range !== undefined) {
      params.date_range = filterForm.date_range;
    }
    if (filterForm.has_suspected !== null) {
      params.has_suspected = filterForm.has_suspected;
    }

    const { data } = await getAssetTasks(params);

    if (data) {
      // 更新全局统计
      if (data.global_stats) {
        globalStats.total_tasks = data.global_stats.total_tasks || 0;
        globalStats.total_suspected = data.global_stats.total_suspected || 0;
        globalStats.total_inferred = data.global_stats.total_inferred || 0;
        globalStats.total_confirmed = data.global_stats.total_confirmed || 0;
      }

      // 更新任务列表
      if (data.items && Array.isArray(data.items)) {
        taskList.value = data.items;
      }

      // 更新分页信息
      if (data.pagination) {
        pagination.total = data.pagination.total || 0;
        pagination.currentPage = data.pagination.page || 1;
        pagination.pageSize = data.pagination.page_size || 10;
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取任务列表失败");
  } finally {
    loading.value = false;
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.keyword = "";
  filterForm.date_range = 7;
  filterForm.has_suspected = null;
  filterForm.sort_by = "scan_time";
  filterForm.sort_order = "desc";
  pagination.currentPage = 1;
  fetchTaskList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchTaskList(values);
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchTaskList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTaskList();
};

// 查看详情
const handleViewDetail = async (row: any) => {
  currentTask.value = row;
  detailVisible.value = true;

  // 调用接口获取详情
  if (row?.task) {
    detailLoading.value = true;
    try {
      const { data } = await getAssetTaskDetail(row.task);
      if (data) {
        taskDetail.value = data;
      } else {
        // 如果没有详情数据，使用列表数据
        taskDetail.value = row;
      }
    } catch (error: any) {
      ElMessage.error(error?.message || "获取任务详情失败");
      // 失败时使用列表数据作为fallback
      taskDetail.value = row;
    } finally {
      detailLoading.value = false;
    }
  } else {
    // 如果没有 task ID，直接使用列表数据
    taskDetail.value = row;
  }
};

// 导出报告
const handleExportReport = async (taskId: string) => {
  if (!taskId) {
    ElMessage.warning("任务ID不存在");
    return;
  }

  try {
    const blob = await exportAssetTaskReport(taskId, "excel");

    // 创建下载链接
    const url = URL.createObjectURL(blob as any);
    const a = document.createElement("a");
    a.href = url;
    const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
    a.download = `任务报告_${taskId}_${date}.xlsx`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  }
};

// 监听弹窗关闭，清空数据
watch(detailVisible, (newVal) => {
  if (!newVal) {
    // 弹窗关闭时清空数据
    taskDetail.value = null;
    currentTask.value = null;
  }
});

// 初始化
onMounted(() => {
  fetchTaskList();
});
</script>

<style scoped lang="scss">
.asset-tasks-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .list-title {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
      color: #303133;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 200px;
  }

  .no-risk {
    color: #909399;
    font-size: 12px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
